#include "rf433.h"
#include "stm32f10x.h"
#include "appconfig.h"
#include "rtdevice.h"
#include "comm.h"


#define RF433_DATA_PIN	  15
#define TEST_OUT_PIN			59//43

static rt_uint32_t periodCnt = 0;
static rt_sem_t recvFinshSem = RT_NULL;

void show_hw_freq(void)
{
	RCC_ClocksTypeDef value;
	
	RCC_GetClocksFreq(&value);
	rt_kprintf("SYSCLK_Frequency = %d\n",value.SYSCLK_Frequency);
	rt_kprintf("PCLK2_Frequency = %d\n",value.PCLK2_Frequency);
	rt_kprintf("PCLK1_Frequency = %d\n",value.PCLK1_Frequency);
	rt_kprintf("HCLK_Frequency = %d\n",value.HCLK_Frequency);
}

rt_uint8_t testvalue = 0;


void TIM4_IRQHandler(void)
{
	rt_interrupt_enter();
	
	if(TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
	{
		TIM_ClearITPendingBit(TIM4,TIM_IT_Update);//清除更新中断标志位
		periodCnt++;
	}
	
	rt_interrupt_leave();
}

/**********************************************************
** 函数名: TIM6_Int_Init
** 功能描述:  基本定时器配置
** 输入参数: 无
** 输出参数: 无
** 说明：定时时间=(预分频数+1）*（计数值+1) /TIM6时钟(72MHz)，单位(s)
   这里溢出时间t=(7200*10000)/72000000s=1s
***********************************************************/
void TIM4_Int_Init(u16 arr,u16 psc)
{
	TIM_TimeBaseInitTypeDef    TIM_TimeBaseStructure;
	NVIC_InitTypeDef           NVIC_InitStructure;
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //使能TIM6时钟
	
	//定时器TIM6初始化
	TIM_TimeBaseStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值	
	TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置用来作为TIMx时钟频率除数的预分频值
	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM向上计数模式
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);  //根据指定的参数初始化TIMx的时间基数单位
	
	//允许更新中断，触发方式中断
	//TIM_ITConfig(TIM4,TIM_IT_Update, ENABLE);     //使能指定的TIM6中断,允许更新中断
//	TIM_ITConfig(TIM6,TIM_IT_Trigger,ENABLE);
	
	//中断优先级NVIC设置
	NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;  //TIM3中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;  //先占优先级0级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;  //从优先级3级
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
	NVIC_Init(&NVIC_InitStructure);
	
	TIM_Cmd(TIM4, ENABLE);     //使能定时器6
}


rt_uint32_t historyValue = 0;
rt_uint8_t  startFlag = 0;
rt_uint8_t datPos = 0;
rt_uint8_t showFlag = 0;
rt_uint8_t recvBitLen = 4*16+8+1;



typedef struct 
{
	rt_uint32_t cntData;
	rt_uint8_t pinValue;
}waveTypeDef;

waveTypeDef wave[500] = {0};


void rt433_pin_interrupt(void *arg)
{
	rt_uint32_t value;

	switch(startFlag)
	{
		case 0:
		{
			wave[0].pinValue = rt_pin_read(RF433_DATA_PIN);
			if(wave[0].pinValue == 0)
			{
				periodCnt = 0;
				historyValue = 0;
				startFlag = 1;
				datPos = 0;
				TIM_ITConfig(TIM4,TIM_IT_Update, ENABLE); 
			}
			break;
		}
		case 1:
		{
			value = periodCnt - historyValue;
			historyValue = periodCnt;
			if(value > 78 && value < 90)
			{
				wave[0].cntData = value;
				wave[0].pinValue = rt_pin_read(RF433_DATA_PIN);
				startFlag = 2;
			}
			else
			{
				startFlag = 0;
				TIM_ITConfig(TIM4,TIM_IT_Update, DISABLE); 
			}
			break;
		}
		case 2:
		{
			value = periodCnt - historyValue;
			if(value < 5 || value > 20)
			{
				startFlag = 0;
				datPos = 0;
				TIM_ITConfig(TIM4,TIM_IT_Update, DISABLE); 
				break;
			}
			historyValue = periodCnt;
			datPos++;
			wave[datPos].cntData = value;
			wave[datPos].pinValue = rt_pin_read(RF433_DATA_PIN);
			if(datPos >= recvBitLen)
			{
				startFlag = 0;
				datPos = 0;
				rt_sem_release(recvFinshSem);//释放接收完成信号量
				TIM_ITConfig(TIM4,TIM_IT_Update, DISABLE); 
			}
			else
			{
				
			}
			break;
		}
	}
}

int rf433_pin_init(void)
{
	rt_pin_mode(RF433_DATA_PIN,PIN_MODE_INPUT); //开机脚
	rt_pin_attach_irq(RF433_DATA_PIN,PIN_IRQ_MODE_RISING_FALLING,rt433_pin_interrupt,RT_NULL);
	rt_pin_irq_enable(RF433_DATA_PIN,PIN_IRQ_ENABLE);
										
	return 0;
}

void show_wave_value(rt_uint16_t size)
{
	rt_uint16_t i;

	for(i=0;i<32;i++)
	{
		rt_kprintf("%4d",i);
	}
	rt_kprintf("\n\r");

	rt_kprintf("%4d",wave[0].cntData);
	rt_kprintf("%c",wave[0].pinValue == 0?'H':'L');
	rt_kprintf("%4d",wave[1].cntData);
	rt_kprintf("%c",wave[1].pinValue == 0?'H':'L');
	rt_kprintf("\n\r");
	for(i=2;i<size+2;i++)
	{
		rt_kprintf("%4d",wave[i].cntData);
		//printf("%c",wave[i].pinValue == 0?'H':'L');
		if(i%32 == 0)
		{
			rt_kprintf("\n\r");
		}
	}
	rt_kprintf("\n\r");
	for(i=0;i<size;i++)
	{
		//printf("%c",wave[i].pinValue == 1?'H':'L');
	}
	rt_kprintf("\n\r");
}


void decode_wave_data(rt_uint8_t result[],rt_uint16_t size)
{
	rt_uint16_t i;
	rt_uint8_t value = 0;
	rt_uint16_t pos = 0;
	
	result[0] = 1;

	//rt_kprintf("Reast Data>>>:");
	for(i=2;i<=72;i+=2)
	{
		if(wave[i].cntData > wave[i+1].cntData)
		{
			value |= 0x01;
		}
		else
		{
			value &= (~0x01);
		}
		value <<= 1;
		if(pos++ == 7)
		{
			//rt_kprintf(" %x ",value);
			result[result[0]++] = value;
			pos = 0;
			value = 0;
		}
	}
	result[result[0]++] = value;
	//rt_kprintf("%x%x%x%x%x%x\n",result[0],result[1],result[2],result[3],result[4],result[5]);
	result[0] = 0;
	//rt_kprintf("%x ",value);
	//rt_kprintf("\r\n");
}

//波形转换成美安数据
void wave_to_value(rt_uint8_t src[],rf433MeiAnDef *data)
{
	data->id = str_to_uint32(src);
	data->value[0] = src[4];
	data->value[1] = src[5];
}

void show_rf433Hex(rf433MeiAnDef *data)
{
	rt_kprintf("ID: %d ",data->id);
	rt_kprintf("%x %x\n",data->value[0],data->value[1]);
}

int rt_hw_rf433_init(void)
{
	rf433_pin_init();
	//rt_pin_mode(TEST_OUT_PIN,PIN_MODE_OUTPUT); //开机脚
  return RT_TRUE;
}
INIT_DEVICE_EXPORT(rt_hw_rf433_init);


void rf433_thread_entry(void *arg)
{
	rf433MeiAnDef history;
	rt_uint8_t over = 0;
	
	rt_kprintf("%s\n",__FUNCTION__);
	TIM4_Int_Init(49,71);//50us
	rt_hw_rf433_init();
	show_hw_freq();
	while(1)
  {
  	rt_err_t result;
		
  	result = rt_sem_take(recvFinshSem, RT_WAITING_FOREVER);
		if(result == RT_EOK)
		{
			rt_uint8_t wavedata[10];
			rf433MeiAnDef *data;

			data = rt_calloc(1, sizeof(*data));
			RT_ASSERT(data);
			
			//show_wave_value(recvBitLen);
			decode_wave_data(wavedata,recvBitLen);
			wave_to_value(wavedata,data);//转换数据
			show_rf433Hex(data);
			if((history.value[0] != data->value[0]))//新的数据
			{
				//result = rf433_mail_send(data);//发送给协议业务处理线程
				history.id = data->id;
				history.value[0] = data->value[0];
				rt_kprintf("!!!!\n");
			}
			else//相同的
			{
				over++;
				if(over >= 8)
				{
					over = 0;
					history.value[0] = 0;
				}
				//rt_kprintf("ssss %d  %d\n",history.id,history.value[0]);
			}
			rt_free(data);
		}
		else
		{
			rt_thread_delay(1);
		}
  }
}

int rf433_thread_init(void)
{
	rt_thread_t thread_id;

	//接收433完成信号量
	recvFinshSem = rt_sem_create("r433", 0, RT_IPC_FLAG_FIFO);
	RT_ASSERT(recvFinshSem);

	thread_id = rt_thread_create("rf433",
							  rf433_thread_entry,RT_NULL,
							  512,Thread433RXPri,25);
	if(thread_id != RT_NULL)
	{
		rt_thread_startup(thread_id);
	}
	return 0;
}

#ifndef STOP_APP_THREAD
INIT_APP_EXPORT(rf433_thread_init);
#endif


